//
//  ForgetPasswordViewController.m
//  PigMarket
//
//  Created by mac on 2019/3/6.
//  Copyright © 2019 felix.pigmarket.oc. All rights reserved.
//

#import "PhoneViewController.h"
#import "SetUpPasswordViewController.h"
#import "PrefectPersonalInfoViewController.h"
#import "SelectInviterViewController.h"
#import "LoginViewController.h"
#import "VerifyCodeButton.h"

@interface PhoneViewController ()

#define Spacing 30

//手机找回密码lab
@property (nonatomic, strong) UILabel *findlab;

//手机号输入框
@property (nonatomic, strong) UITextField *phoneField;

//手机号输入框下划线
@property (nonatomic, strong) UIView *phoneLine;

//短信验证码输入框
@property (nonatomic, strong) UITextField *verifyField;

//获取验证码btn
@property (nonatomic, strong) VerifyCodeButton *verifyBtn;

//短信验证码下划线
@property (nonatomic, strong) UIView *verifyLine;

//下一步btn
@property (nonatomic, strong) UIButton *nextBtn;

/**
 数据请求的验证码
 */
@property (nonatomic , strong) NSString *messageCode;
@end

@implementation PhoneViewController

#pragma mark - view life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpView];
    self.view.backgroundColor = KWhiteColor;
}



#pragma mark - init method
- (void)setUpView {
    [self initView];
    [self initLayout];
    [self initAction];
    [self initData];
}

//添加子视图
- (void)initView {
    [self.view addSubview:self.findlab];
    [self.view addSubview:self.phoneField];
    [self.view addSubview:self.phoneLine];
    [self.view addSubview:self.verifyField];
    [self.view addSubview:self.verifyBtn];
    [self.view addSubview:self.verifyLine];
    [self.view addSubview:self.nextBtn];
}

//布局
- (void) initLayout {
    [self.findlab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(Spacing);
        make.top.mas_equalTo(30 + TJ_NavBarHeight);
        make.right.mas_equalTo(-Spacing);
        make.height.mas_greaterThanOrEqualTo(0);
    }];
    
    [self.phoneField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(Spacing);
        make.top.equalTo(self.findlab.mas_bottom).offset(39);
        make.right.mas_equalTo(-Spacing);
        make.height.mas_equalTo(54);
    }];
    
    [self.phoneLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(Spacing);
        make.right.mas_equalTo(-Spacing);
        make.top.equalTo(self.phoneField.mas_bottom).offset(1);
        make.height.mas_equalTo(1);
    }];
    
    [self.verifyField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(Spacing);
        make.top.equalTo(self.phoneLine.mas_bottom).offset(14);
        make.height.mas_equalTo(54);
    }];
    
    [self.verifyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.verifyField.mas_centerY);
        make.right.mas_equalTo(-Spacing);
        make.height.mas_equalTo(54);
    }];
    
    [self.verifyLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.verifyField.mas_bottom).offset(0);
        make.right.mas_equalTo(-Spacing);
        make.left.mas_equalTo(Spacing);
        make.height.mas_equalTo(1);
    }];
    
    [self.nextBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.verifyLine).offset(40);
        make.left.mas_equalTo(30);
        make.right.mas_equalTo(-30);
        make.height.mas_equalTo(48);
    }];
}
//定义点击事件
- (void) initAction {
    RACSignal *sendVerifyStateSignal = [self.phoneField.rac_textSignal map:^id _Nullable(NSString * _Nullable phoneNum) {
        return @([phoneNum isValidPhoneNumber]);
    }];
    RACSignal *countDowningSignal = RACObserve(self.verifyBtn, isCountDowning);
    RAC(self.verifyBtn,enabled) = [RACSignal combineLatest:@[sendVerifyStateSignal,countDowningSignal] reduce:^id _Nonnull(NSNumber *sendVerifyState, NSNumber *countDowningState){
        return @(sendVerifyState.boolValue && !countDowningState.boolValue);
    }];
    
    [_verifyBtn addTarget:self action:@selector(verifyClick) forControlEvents:UIControlEventTouchUpInside];

}
//数据请求
- (void)initData {
    
}

#pragma mark - delegate

#pragma mark - target action
- (void)verifyClick {
    NSString *phone = self.phoneField.text;
    if (![phone isValidPhoneNumber]) {
        [self toastWithContent:@"请输入正确的手机号码"];
        return;
    }
    GetMessageCodeParam *param = [[GetMessageCodeParam alloc] init];
    param.phone = phone;
    if ([self.tipsTitle isEqualToString:BindPhoneNumber] || [self.tipsTitle isEqualToString:BindNewPhoneNumber]) {
        //注册和绑定手机号码
        param.type = GetMessageCodeTypeRegisterAndBind;
    } else if ([self.tipsTitle isEqualToString:ModifyPassword]){
        //忘记密码
        param.type = GetMessageCodeTypeChangePassword;
    }
    @weakify(self);
    [[[PigMarketApi sharedInstance] getMessageCodeWithParam:param] subscribeNext:^(GetMessageCode * _Nullable getMessageCode) {
        @strongify(self);
        [self toastWithContent:@"验证码已发送手机，请注意查收"];
        self.messageCode = getMessageCode.mobileCode;
        [self.verifyBtn startCountDown];
    } error:^(NSError * _Nullable error) {
        [self handlingError:error];
    }];
}
- (void)nextClick {
    NSString *phone = self.phoneField.text;
    if (![phone isValidPhoneNumber]) {
        [self toastWithContent:@"请输入正确的手机号码"];
        return;
    }
    if (![self.messageCode isEqualToString:self.verifyField.text]) {
        [self toastWithContent:@"请输入正确的验证码"];
        return;
    }
    if ([self.tipsTitle isEqualToString:BindPhoneNumber]) {
        //绑定手机号 ->注册接口 -> 登录接口(获取memberid)
        [self thirdLoginRegisterWithPhone:phone verifyCode:self.messageCode];
        
    } else if ([self.tipsTitle isEqualToString:ModifyPassword]){
        SetUpPasswordViewController *vc = [[SetUpPasswordViewController alloc] init];
        vc.phone = self.phoneField.text;
        [self.navigationController pushViewController:vc animated:YES];
    } else if ([self.tipsTitle isEqualToString:BindNewPhoneNumber]){
        //设置里 更换手机号码
        [self changePhoneRequestWithPhone:phone];
     }
}

#pragma mark - private method
// ->注册接口 -> 登录接口(获取memberid)
- (void)thirdLoginRegisterWithPhone:(NSString *)phone verifyCode:(NSString *)verifyCode {
    NSString *wechatId = @"";
    NSString *qqId = @"";
    NSString *sinaId = @"";
    if ([self.thirdLoginType intValue] == 1) {//微信
        wechatId = self.uid;
    } else if ([self.thirdLoginType intValue] == 2 ) {//qq
        qqId = self.uid;
    } else if ([self.thirdLoginType intValue] == 4) {//微博 （删除 3:支付宝 ）
        sinaId = self.uid;
    }

    [[[PigMarketApi sharedInstance] userThirdRegisterWithAccount:phone verifyCode:verifyCode wechatId:wechatId qqId:qqId sinaId:sinaId] subscribeNext:^(UserInfo * _Nullable x) {
        
        [self loginToGetUserInfoWithVerifyCode:verifyCode];
    } error:^(NSError * _Nullable error) {
        [self handlingError:error];

    }];
}
//-> 登录接口(获取memberid)
- (void)loginToGetUserInfoWithVerifyCode:(NSString *)verifyCode {
    [[[PigMarketApi sharedInstance] userLoginWithAccount:self.uid msgCode:verifyCode loginType:self.thirdLoginType] subscribeNext:^(UserInfo * _Nullable userInfo) {
        //存数据
        [UserInfoDataProvider sharedInstance].userInfo = userInfo;
        [TokenCacheManager sharedInstance].memberToken = userInfo.memberToken;

        SelectInviterViewController *selectInviterVC = [[SelectInviterViewController alloc] init];
        [self.navigationController pushViewController:selectInviterVC animated:YES];

    } error:^(NSError * _Nullable error) {
        [self handlingError:error];
    }];
}
//更改手机号请求
- (void)changePhoneRequestWithPhone:(NSString *)phone{
    NSNumber *memberId = [UserInfoDataProvider sharedInstance].userInfo.memberId;
    AccountBindParam *param = [[AccountBindParam alloc] init];
    param.account = phone;
    param.type = @(BindAccountTypePhone);
    param.isBind = @(1);
    param.memberId = memberId;
    
    @weakify(self);
    [[[PigMarketApi sharedInstance] accountBindOrUnbindWithParam:param] subscribeNext:^(NSNull * _Nullable x) {
        @strongify(self);
        //改换缓存手机号码
        UserInfo *userInfo = [[UserInfo alloc] init];
        userInfo.phone = phone;
        [UserInfoDataProvider sharedInstance].userInfo = userInfo;
        [self toastWithContent:@"手机号码更改成功"];
        
        //通知上一页面更新手机号
        [[NSNotificationCenter defaultCenter] postNotificationName:NotificationPhoneChanged object:self];
        [self.navigationController popViewControllerAnimated:YES];
        
        
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [self handlingError:error];
    }];
}
//懒加载
#pragma mark - getter and setter
- (UILabel *)findlab {
    if (!_findlab) {
        _findlab = [[UILabel alloc] init];
        _findlab.text = self.tipsTitle;
        _findlab.font = [UIFont systemFontOfSize:22];
        _findlab.textColor = [UIColor colorWithHexString:@"#363636"];
    }
    return _findlab;
}

-(UITextField *)phoneField {
    if (!_phoneField) {
        _phoneField = [[UITextField alloc] init];
        _phoneField.placeholder = @"请输入手机号";
        _phoneField.keyboardType = UIKeyboardTypeNumberPad;
        [_phoneField setValue:[UIFont systemFontOfSize:16] forKeyPath:@"placeholderLabel.font"];
        [_phoneField setValue:[UIColor colorWithHexString:@"#ACACAC"] forKeyPath:@"placeholderLabel.textColor"];

    }
    return _phoneField;
}

- (UIView *)phoneLine {
    if (!_phoneLine) {
        _phoneLine = [[UIView alloc] init];
        _phoneLine.backgroundColor = [UIColor colorWithHexString:@"#000000" alpha:0.08];
    }
    return _phoneLine;
}

- (UITextField *)verifyField {
    if (!_verifyField) {
        _verifyField = [[UITextField alloc] init];
        _verifyField.placeholder = @"请输入短信验证码";
        _verifyField.keyboardType = UIKeyboardTypeNumberPad;
        [_verifyField setValue:[UIFont systemFontOfSize:16] forKeyPath:@"placeholderLabel.font"];
        [_verifyField setValue:[UIColor colorWithHexString:@"#ACACAC"] forKeyPath:@"placeholderLabel.textColor"];
    }
    return _verifyField;
}

- (VerifyCodeButton *)verifyBtn {
    if (!_verifyBtn) {
        _verifyBtn = [VerifyCodeButton buttonWithType:UIButtonTypeCustom];
//        [_verifyBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
//        [_verifyBtn setTitleColor:[UIColor colorWithHexString:@"#8F8F8F"] forState:UIControlStateNormal];
//        _verifyBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    }
    return _verifyBtn;
}

- (UIView *)verifyLine {
    if (!_verifyLine) {
        _verifyLine = [[UIView alloc] init];
        _verifyLine.backgroundColor = [UIColor colorWithHexString:@"#000000" alpha:0.08];
    }
    return _verifyLine;
}

- (UIButton *)nextBtn {
    if (!_nextBtn) {
        _nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_nextBtn setBackgroundImage:[UIImage imageNamed:@"login_loginbtn_default"] forState:UIControlStateNormal];
        [_nextBtn setBackgroundImage:[UIImage imageNamed:@"login_selected"] forState:UIControlStateHighlighted];
        [_nextBtn setTitle:@"下一步" forState:UIControlStateNormal];
        _nextBtn.titleLabel.font = [UIFont boldSystemFontOfSize:16];
        [_nextBtn addTarget:self action:@selector(nextClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _nextBtn;
}
@end
